package com.yyw.gulimall.cart.interceptor;

import com.yyw.common.constant.auth.AuthServerConstant;
import com.yyw.common.constant.common.UrlConstant;
import com.yyw.common.to.oauth.MemberVo;
import com.yyw.gulimall.cart.to.UserInfoTo;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

/**
 * @Classname CartInterceptor
 * @Description 拦截器
 * 在执行目标方法之前，判断用户的登录状态。并封装传递给目标请求
 * 拦截所有请求，判断用户是否登录，登陆了填充用户ID，
 * 否则就是离线购物车，随机给user-key 标识用户身份
 * 并且放在LocalThread中，达到同一个线程共享数据
 * @Date 2020/12/21 13:53
 * @Created yyw
 */
public class CartInterceptor implements HandlerInterceptor {
    //ThreadLocal同一个线程共享数据
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 执行方法之前
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo infoTo = new UserInfoTo();
        MemberVo user = (MemberVo) request.getSession().getAttribute(AuthServerConstant.SESSION_LOGIN_USER);
        if (null != user) {
            infoTo.setUserId(user.getId());
        }

        // 判断cookie中是否存在用户信息
        Cookie[] cookies = request.getCookies();
        if (null != cookies && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (Objects.equals(cookie.getName(), AuthServerConstant.CART_OFF_LINE_USER)) {
                    infoTo.setUserKey(cookie.getValue());
                }
            }
        }

        // 如果上一步没有，则颁发一个user-key
        if (Objects.equals(null, infoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            infoTo.setUserKey(uuid);
            // 修改为临时用户
            infoTo.setTempUser(true);
        }

        // 放置线程共享区中
        threadLocal.set(infoTo);
        return true;
    }

    /**
     * 执行方法之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 判断是否需要将user-key放置cookie中,临时用户
        UserInfoTo infoTo = threadLocal.get();
        if (infoTo.isTempUser()) {
            Cookie cookie = new Cookie(AuthServerConstant.CART_OFF_LINE_USER, infoTo.getUserKey());
            cookie.setDomain(UrlConstant.COOKIE_DOMAIN_URL);
            // 设置过期时间 30天
            cookie.setMaxAge(60*60*24*30);
            cookie.setPath("/");
            response.addCookie(cookie);
            System.out.println("我发了userKey。。。");
        }
    }
}
